package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Component
public class OrderReceiver {

    @Autowired
    private OrderInfoService orderInfoService;

    //  监听取消订单; 使用延迟消息；一种：死信队列；一种延迟插件; A：10s  B:5s;
    @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
    public void orderCancel(String orderNo, Message message, Channel channel){
        try {
            System.out.println("订单取消了");
            //  判断orderNo 是否为空
            if (!StringUtils.isEmpty(orderNo)){
                //  调用服务层方法.
                orderInfoService.orderCancel(orderNo);
            }
        } catch (Exception e) {
            //  异常信息；
            System.out.println(e.getMessage());
        }
        //  手动确认;
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_ORDER, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_ORDER_PAY_SUCCESS, durable = "true"),
            key = {MqConst.ROUTING_ORDER_PAY_SUCCESS}
    ))
    public void orderPaySuccess(String orderNo, Message message, Channel channel) {
        //业务处理
        if (StringUtils.hasText(orderNo)) {
            orderInfoService.orderPaySuccess(orderNo);
        }

        //手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


}